import java.util.ArrayList;
import java.util.List;

//在每个树行中找最大值
//测试链接 https://leetcode.cn/problems/find-largest-value-in-each-tree-row/
public class LargestValues {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;

        TreeNode[] q = new TreeNode[10001]; //用数组模拟队列
        int l = 0, r = 0;
        q[r++] = root;
        while(l < r){
            int n = r - l;
            int max = q[l].val; //标记每一层的最大值
            while(n-- != 0) {
                TreeNode node = q[l++];
                if(node.val > max) {
                    max = node.val;
                }

                if(node.left != null) q[r++] = node.left;
                if(node.right != null) q[r++] = node.right;
            }
            ret.add(max);
        }
        return ret;
    }
}
